from main import setup
from .clinet import Clinet
from .info import Info
from . import constants as C
import pygame


class Snake:
    def __init__(self, clinet):
        self.finished = False
        self.next = "over"
        # self.info = Info("gaming")
        self.clinet = clinet
        self.keys_buff = []
        self.frame_of_9 = 1
        self.score = 0
        # self.timer = 0

    def update_keys(self, keys):
        self.key_list = []
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.key_list.append(C.LEFT)
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.key_list.append(C.RIGHT)
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.key_list.append(C.UP)
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.key_list.append(C.DOWN)
        if keys[pygame.K_SPACE]:
            self.key_list.append(C.SPACE)
        if self.key_list:
            self.keys_buff = self.key_list

    #画出所有蛇
    def draw_snakes(self, snakes, my_id, surface):
        snake_count = len(snakes)
        for i in range(snake_count):
            if my_id == i:
                color = C.MY_COLOR
            else:
                color = C.ENEMY_COLOR
            for xy in snakes[i]:
                self.draw(xy, color, surface)

    #画出食物
    def draw_food(self, food, surface):
        for xy in food:
            self.draw(xy, C.FOOD_COLOR, surface)

    #判断是否鼠标关闭游戏窗口,避免死机
    def game_closed_by_X(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True

    def draw(self, xy, color, surface):
        pygame.draw.rect(
            surface, color,
            (xy[0], xy[1], C.BOX_SIZE, C.BOX_SIZE))  #在xy坐标画出一格color颜色的格子

    def update(self, surface, keys):  # while True:

        self.update_keys(keys)
        if self.frame_of_9 % 3 == 0:
            surface.fill(C.SCREEN_COLOR)
            if not self.keys_buff:
                self.keys_buff.append(C.NO_KEY)
            if self.frame_of_9 % 9 == 0:  #若是第9帧发的信息，添加第9帧标识
                self.keys_buff.append(9)
            data = str(self.keys_buff) + "|"  #"|"分隔符
            data = data.replace(" ", "")  #去掉空格
            setup.connection.sendall(str.encode(data))  #发送给服务器
            # print(data)
            self.keys_buff.clear()  #清空按键缓存

            #接收来自服务器的信息，画出图形
            data = setup.connection.recv(8192).decode()
            # print("got msg\data: " + data)
            if data.startswith("msg(游戏结束)"):  #如果收到附加信息，做处理
                score = int(data[25:]) - 1
                self.score = score
                print("score", score)
                # self.info = Info("over", score)
                self.finished = True
            else:
                snakes, food = self.clinet.unpack_map_data(data)
                # snakes ,food = ()
                self.draw_snakes(snakes, self.clinet.my_id, surface)
                self.draw_food(food, surface)
        if self.frame_of_9 == 9:  #第9帧结束，复原帧的标记
            self.frame_of_9 = 1
        else:  #普通帧结束，帧数自加1
            self.frame_of_9 += 1
